package com.example.vertification.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.UUID;

@RestController
@Api(value = "语音识别", tags = "语音识别")
public class VoiceController {

//    @PostMapping("contact")
    @PostMapping("/voice")
    public ResponseEntity<?> voice(@RequestParam("audioFile") MultipartFile file) throws IOException {
     if (file.isEmpty()) {
         JSONObject obj = JSONUtil.createObj();
         obj.set("status","201");
         obj.set("result","文件为空");
         return new ResponseEntity<>(obj, HttpStatus.OK);
     }
     String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
     String tempDir = System.getProperty("java.io.tmpdir");
     File tempFile = new File(tempDir, fileName);
     try {
      // 将上传的文件保存到临时文件中
      file.transferTo(tempFile);
     } catch (IOException e) {
      throw new RuntimeException(e);
     }
     byte[] fileContent = Files.readAllBytes(Paths.get(tempFile.getPath()));
     String base64 = Base64.getEncoder().encodeToString(fileContent);
        String URL = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={appid}&client_secret={key}";
        String appid = "语音识别appid";
        String key = "语音识别key";
        String Access_token =  new JSONObject(HttpUtil.get(URL.replace("{key}",key).replace("{appid}",appid))).getStr("access_token");
        String Send_To_Url = "http://vop.baidu.com/server_api";
        JSONObject message = new JSONObject();
        message.set("format", "wav");
        message.set("rate", 16000);
        message.set("dev_pid", 1537);
        message.set("channel", 1);
        message.set("token", Access_token);
        message.set("cuid", UUID.randomUUID());
        message.set("len", fileContent.length);
        message.set("speech",base64);
        // 将JSON对象转换为字符串
        String jsonStr = message.toString();
        JSONObject result_obj = JSONUtil.parseObj(HttpRequest.post(Send_To_Url)
                .header("Content-Type", "application/json")
                .body(jsonStr)
                .execute()
                .body());

        tempFile.delete();
        JSONObject obj = JSONUtil.createObj();
        obj.set("status","200");
        String str = result_obj.getStr("result").replace("\"", "").replace("[", "").replace("]", "");;
        obj.set("result",str);
        return new ResponseEntity<>(obj, HttpStatus.OK);
    }






}
